package br.com.rhweb.util;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;

import br.com.rhweb.dao.Dao;
import br.com.rhweb.dao.IDao;
import br.com.rhweb.hibernate.HibernateUtil;
import br.com.rhweb.modelos.Bairro;
import br.com.rhweb.modelos.Endereco;

public class ExportaEnderecos {

	
	public static void main(String[] args) {
		PreparedStatement pstm ;
		final ResultSet rs;

		String sql = "SELECT * FROM tbl_endereco LIMIT 414310, 805689";
		
		try {
			pstm = ConexaoJDBC.getConnection().prepareStatement(sql);
			rs = pstm.executeQuery();
			new Thread(){
				public void run(){
					try {
						while(rs.next()){
							Session ss = null;
							Session s = null;
							IDao<Endereco> dao;
							IDao<Bairro> daoBairroDao;
							
							Endereco endereco;
							Bairro bairro;
							
							ss = HibernateUtil.getSessionfactory().openSession();
							ss.beginTransaction();

							daoBairroDao = new Dao<Bairro>(ss, Bairro.class);
							dao = new Dao<Endereco>(s, Endereco.class);
							
							endereco = new Endereco();							
							endereco.setCep(rs.getString("cep_endereco"));
							endereco.setLogradouro(rs.getString("logradouro_endereco"));
							bairro = daoBairroDao.load(rs.getInt("id_bairro"));
							ss.getTransaction().commit();
							endereco.setBairro(bairro);
							s = HibernateUtil.getSessionfactory().openSession();
							s.beginTransaction();
							dao.save(endereco);						
							s.getTransaction().commit();						
							//enderecos.add(endereco);
							try{
								sleep(5);
							}catch (Exception e) {
								System.out.println("Erro: "+e.getMessage());
							}
						}
					} catch (HibernateException e) {
						System.out.println("Hibernate Exception Message: "+e.getMessage());
						System.out.println("Hibernate Exception Cause: "+e.getCause());
					} catch (SQLException e) {
						System.out.println("SQLException Exception Message: "+e.getMessage());
						System.out.println("SQLException Exception Cause: "+e.getCause());
					}
				}	
			}.start();	

			ConexaoJDBC.getConnection().close();
			/*for(Endereco e : enderecos){
				s = HibernateUtil.getSessionfactory().openSession();
				s.beginTransaction();
				System.out.println(e.getCep());
				dao = new Dao<Endereco>(s, Endereco.class);
				dao.save(e);
				s.getTransaction().commit();
			}*/
			
		} catch (SQLException e) {
			//s.getTransaction().rollback();
			System.out.println("Erro: "+e.getMessage());
		}

	}
	
	
}
